package com.lic.license.core;



import com.lic.license.manager.LicenseManagerHolder;
import com.lic.license.param.CustomKeyStoreParam;
import de.schlichtherle.license.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.prefs.Preferences;

/**
 * <p>License校验类</p>
 */
@Component
public class LicenseVerify {

    private static Logger logger = LogManager.getLogger(LicenseVerify.class);
    /**
     * 证书subject
     */
    @Value("${license.subject}")
    private String subject;

    /**
     * 公钥别称
     */
    @Value("${license.publicAlias}")
    private String publicAlias;

    /**
     * 访问公钥库的密码
     */
    @Value("${license.storePass}")
    private String storePass;

    /**
     * 证书生成路径
     */
    @Value("${license.licensePath}")
    private String licensePath;

    /**
     * 密钥库存储路径
     */
    @Value("${license.publicKeysStorePath}")
    private String publicKeysStorePath;

    /**
     * 标识证书是否安装成功
     */
    private boolean installSuccess;



    /**
     * 安装License证书，读取证书相关的信息, 在bean加入容器的时候自动调用
     */
    @PostConstruct
    public void installLicense() {
        try {
            //初始化证书参数
            Preferences preferences = Preferences.userNodeForPackage(LicenseVerify.class);

            CipherParam cipherParam = new DefaultCipherParam(storePass);

            KeyStoreParam publicStoreParam = new CustomKeyStoreParam(LicenseVerify.class,
                    publicKeysStorePath,
                    publicAlias,
                    storePass,
                    null);
            LicenseParam licenseParam = new DefaultLicenseParam(subject, preferences, publicStoreParam, cipherParam);
            //结束
            LicenseManager licenseManager = LicenseManagerHolder.getInstance(licenseParam);
            //卸载证书
            licenseManager.uninstall();
            File file = new File(licensePath);
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
            }catch (FileNotFoundException e){
                throw new LicenseContentException("授权文件不存在");
            }
            LicenseContent licenseContent = licenseManager.install(file);
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            installSuccess = true;
            logger.info("------------------------------- 证书安装成功 -------------------------------");
            logger.info(MessageFormat.format("证书有效期：{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));
        } catch (Exception e) {
            installSuccess = false;
            logger.error("------------------------------- 证书安装失败 -------------------------------");
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 校验License证书
     */
    public boolean verify() throws Exception {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LicenseContent licenseContent = LicenseManagerHolder.getLicenseManager().verify();
        if (licenseContent == null) {
            return false;
        } else {
            logger.info(MessageFormat.format("证书校验通过，证书有效期：{0} - {1}", format.format(licenseContent.getNotBefore()), format.format(licenseContent.getNotAfter())));
            return true;
        }

    }




}

